//index.js
const app = getApp()
var refresh = function(that) {
  wx.request({
    url: getApp().data.servser + '/trip/list',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Authorization': 'Bearer ' + wx.getStorageSync('token')
    },
    data: {
      username: that.data.username
    },
    success: function(res) {
      that.setData({
        need_login: 'no',
        tripInfoList: res.data.data.tripInfoList,
        today: res.data.data.today,
        now: res.data.data.now,
        order_data: res.data.data.today,
        order_time: res.data.data.now,
        end: res.data.data.end
      })
    }
  })

}
Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    requestResult: '',
    need_login: 'yes',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    username: '',
    password: '',
    istrue: false,
    today: '',
    order_data: '',
    order_time: '',
    end: '',
    order_time: '点我选择预约时间，立即降锁无需选择。'
  },
  getInputUserId: function(e) {
    this.data.username = e.detail.value;
  },
  getInputPwd: function(e) {
    this.data.password = e.detail.value;
  },
  onPullDownRefresh: function() {
    var that = this;
    refresh(that)
  },
  register: function(e) {
    wx.navigateTo({
      url: 'register',
    })
  },
  cancleOrBegin:function(e){
    this.setData({
      istrue: true,
      car_out: 'off',
      cancleOrBegin:'on',
      parking_place_id: e.currentTarget.dataset.id
    })
  },
  out: function(e) {
    console.log(this.data.needPayPrice);
    this.setData({
      istrue: true,
      car_out: 'on',
      cancleOrBegin: 'off',
      parking_place_id: e.currentTarget.dataset.id
    })
  },
  parktap: function(e) {
    if(e.currentTarget.dataset.status!=0){
      return;
    }else{
      wx.navigateTo({
        url: 'parkingplace/detail?id=' + e.currentTarget.dataset.id,
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
    }
    // this.setData({
    //   istrue: true,
    //   car_out: 'off',
    //   cancleOrBegin: 'off',
    //   parking_place_id: e.currentTarget.dataset.id
    // })
  },
  closeDialog: function() {
    this.setData({
      istrue: false
    })
  },
  bindGetUserInfo(e) {
    var that = this;
    if (this.data.username.length <= 0) {
      wx.showToast({
        title: '请输入用户名!',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    if (this.data.password.length <= 0) {
      wx.showToast({
        title: '请输入密码!',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    wx.request({
      url: getApp().data.servser + '/auth',
      method: 'GET',
      data: {
        username: that.data.username,
        password: that.data.password
      },
      success: function(res) {
        if (res.data.code == 500) {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
          // 登录失败
          that.setData({
            need_login: 'yes'
          })
        } else {
          var token = res.data.token;
          wx.request({
            url: getApp().data.servser + '/trip/list',
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Authorization': 'Bearer ' + token
            },
            data: {
              username: that.data.username
            },
            success: function(res) {
              wx.setStorageSync('token', token);
              wx.setStorageSync('username', that.data.username);
              wx.setStorageSync('password', that.data.password);
              that.setData({
                need_login: 'no',
                tripInfoList: res.data.data.tripInfoList,
                today: res.data.data.today,
                now: res.data.data.now,
                order_data: res.data.data.today,
                order_time: res.data.data.now,
                end: res.data.data.end
              })
            }
          })



        }
      }
    });
  },
  beginUse:function(){
    var that = this;
    wx.request({
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      url: getApp().data.servser + '/parking/place/use/begin/use',
      method: 'POST',
      data: {
        parkingPlaceId: that.data.parking_place_id,
        parkingId: that.data.parkingInfo.seqId,
        openId: app.globalData.openid
      },
      success: function (res) {
        wx.showToast({
          title: '车位降锁成功!',
          icon: 'none',
          duration: 2000
        })
        wx.reLaunch({
          url: 'parking?id=' + that.data.parkingInfo.seqId,
        })
      }
    })
  },
  cancelOrder:function(){
    var that = this;
    wx.request({
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      url: getApp().data.servser + '/parking/place/use/cancel/order',
      method: 'POST',
      data: {
        parkingPlaceId: that.data.parking_place_id,
        parkingId: that.data.parkingInfo.seqId,
        openId: app.globalData.openid
      },
      success: function (res) {
        wx.showToast({
          title: '车位释放成功!',
          icon: 'none',
          duration: 2000
        })
        wx.reLaunch({
          url: 'parking?id=' + that.data.parkingInfo.seqId,
        })
      }
    })
  },
  carOut: function() {
    var that = this;
    wx.request({
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      url: getApp().data.servser + '/parking/place/use/car/out',
      method: 'POST',
      data: {
        parkingPlaceId: that.data.parking_place_id,
        parkingId: that.data.parkingInfo.seqId,
        openId: app.globalData.openid,
        money: that.data.needPayPrice
      },
      success: function(res) {
        if(res.data.code == 500){
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }else{
          wx.showToast({
            title: '车位释放成功!',
            icon: 'none',
            duration: 2000
          })
          wx.reLaunch({
            url: 'parking?id=' + that.data.parkingInfo.seqId,
          })
        }

      }
    })
  },
  useNow: function() {
    var that = this;
    wx.request({
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      url: getApp().data.servser + '/parking/place/use/use/now',
      method: 'POST',
      data: {
        parkingPlaceId: that.data.parking_place_id,
        parkingId: that.data.parkingInfo.seqId,
        openId: app.globalData.openid,
        payFlag: '1'
      },
      success: function(res) {
        if (res.data.code == 500) {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '车位降锁成功!',
            icon: 'none',
            duration: 2000
          })
          that.setData({
            istrue: false
          })
          wx.reLaunch({
            url: 'parking?id=' + that.data.parkingInfo.seqId,
          })
        }
      }
    })
  },
  useLater: function() {
    var that = this;
    let order_time = (this.data.order_time)
    if (order_time == '点我选择预约时间，立即降锁无需选择。') {
      wx.showToast({
        title: '请选择预约时间!',
        icon: 'none',
        duration: 2000
      })
    } else {
      wx.request({
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        url: getApp().data.servser + '/parking/place/use/order',
        method: 'POST',
        data: {
          orderTime: that.data.order_time,
          parkingPlaceId: that.data.parking_place_id,
          parkingId: that.data.parkingInfo.seqId,
          openId: app.globalData.openid,
          payFlag: '1'
        },
        success: function(res) {
          if (res.data.code == 500) {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '车位预约成功!',
              icon: 'none',
              duration: 2000
            })
            that.setData({
              istrue: false
            })
            wx.reLaunch({
              url: 'parking?id=' + that.data.parkingInfo.seqId,
            })
          }
        }
      })
    }
  },
  onLoad: function(options) {
    var that = this;
    console.log(options.id)
    wx.request({
      url: getApp().data.servser + '/parking/detail',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      data: {
        openId: app.globalData.openid,
        seqId: options.id
      },
      success: function(res) {
        let distance = Math.trunc(that.juli(res.data.data.parkingInfo.latitude, res.data.data.parkingInfo.longitude, app.globalData.latitude, app.globalData.longitude)) + '公里'
        that.setData({
          parkingInfo: res.data.data.parkingInfo,
          parkingPlaceInfoList: res.data.data.parkingPlaceInfoList,
          distance: distance,
          free: res.data.data.free,
          now: res.data.data.now,
          end: res.data.data.end,
          parkingPlaceUseInfo: res.data.data.parkingPlaceUseInfo,
          total: res.data.data.parkingPlaceInfoList.length,
          needPayPrice: res.data.data.needPayPrice
        })
      }
    })
  },
  bindTimeChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      order_time: e.detail.value
    })
  },
  //导航
  nav: function(e) {
    //使用微信内置地图查看位置，地点的经纬度可用腾讯地图坐标拾取器获取（https://lbs.qq.com/tool/getpoint/）
    wx.getLocation({ //获取当前经纬度
      type: 'wgs84', //返回可以用于wx.openLocation的经纬度，官方提示bug: iOS 6.3.30 type 参数不生效，只会返回 wgs84 类型的坐标信息
      success: function(res) {
        wx.openLocation({ //?使用微信内置地图查看位置。
          latitude: Number(e.currentTarget.dataset.latitude), //要去地点的纬度
          longitude: Number(e.currentTarget.dataset.longitude), ///要去地点的经度-地址
          name: e.currentTarget.dataset.name, //
          address: e.currentTarget.dataset.address
        })
      }
    })
  },
  juli(lat1, lng1, lat2, lng2) {
    console.log(lat1 + " " + lng1)
    console.log(lat2 + " " + lng2)
    var radLat1 = lat1 * Math.PI / 180.0;
    var radLat2 = lat2 * Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    return s
  },
  onGetUserInfo: function(e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },

  onGetOpenid: function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '../userConsole/userConsole',
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },

  // 上传图片
  doUpload: function() {
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {

        wx.showLoading({
          title: '上传中',
        })

        const filePath = res.tempFilePaths[0]

        // 上传图片
        const cloudPath = 'my-image' + filePath.match(/\.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上传文件] 成功：', res)

            app.globalData.fileID = res.fileID
            app.globalData.cloudPath = cloudPath
            app.globalData.imagePath = filePath

            wx.navigateTo({
              url: '../storageConsole/storageConsole'
            })
          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })

      },
      fail: e => {
        console.error(e)
      }
    })
  },

})